/*******************************************************************************
 * Package: com.chris.gateway.predicates
 * Type:    AgeRoutePredicateFactory
 * Date:    2024/3/7 下午12:42
 *
 * Copyright (c) 2024 BOING CORP.,LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.chris.gateway.predicates;

import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * 自定义Age断言类,别忘了使用注解使spring生成一个bean
 *
 * @author Hudesheng
 * @date 2024/3/7 下午12:42
 */
@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {
    public AgeRoutePredicateFactory() {
        super(AgeRoutePredicateFactory.Config.class);
    }
    
    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                //从serverWebExchange获取传入的参数
                String agestr = serverWebExchange.getRequest().getQueryParams().getFirst("age");
                //有age参数按指定规则校验
                if(StringUtils.isNotEmpty(agestr)){
                    int age = Integer.parseInt(agestr);
                    return age > config.getMinAge() && age < config.getMaxAge();
                }
                //没有age参数则不校验
                return true;
            }
        };
    }
    
    @Override
    public List<String> shortcutFieldOrder() {
        //这里的顺序要跟配置文件中的参数顺序一致
        return Arrays.asList("minAge", "maxAge");
    }
    
    @Data
    public static class Config{
        private int minAge;
        private int maxAge;
    }
}